/*******************************************************************************
 * Package: com.song.boot.springstudy.marshall
 * Type:    ServerHandler
 * Date:    2024-01-28 16:18
 *
 * Copyright (c) 2024 LTD All Rights Reserved.
 *
 * You may not use this file except in compliance with the License.
 *******************************************************************************/
package com.song.boot.springstudy.netty.proto;

import com.song.boot.springstudy.netty.marshall.ReqData;
import com.song.boot.springstudy.netty.marshall.RespData;
import com.song.boot.springstudy.netty.proto.protoDoMain.CatInfo;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;
import io.netty.util.ReferenceCountUtil;

/**
 * 功能描述：
 *
 * @author Songxianyang
 * @date 2024-01-28 16:18
 */
public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg){
        try {
            CatInfo.CatMsg reqData=  (CatInfo.CatMsg)msg;
            System.out.println("接收到客户端消息"+reqData.getId());
            System.out.println("接收到客户端消息"+reqData.getName());
            System.out.println("接收到客户端消息"+reqData.getAge());

        }finally {
            ReferenceCountUtil.release(msg);
        }
    }
    // 发生异常，则关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }

    // 读事件完毕，发送数据回复给客户端
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("读取client数据成功。返回给客户端的ack", CharsetUtil.UTF_8));
        System.out.println("ack");
    }
}
